import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import { Container } from '@/components/common/container';
import { X, Plus } from 'lucide-react';

const ProjectForm = ({ project, onSubmit, onCancel }) => {
  const [formData, setFormData] = useState({
    project_name: '',
    project_type: '',
    priority: '中',
    status: '立项',
    manager_name: '',
    client_info: '',
    start_date: '',
    end_date: '',
    budget: '',
    description: '',
    objectives: '',
    risk_level: '中',
    team_members: []
  });

  const [newMember, setNewMember] = useState('');
  const [loading, setLoading] = useState(false);

  // 初始化表单数据
  useEffect(() => {
    if (project) {
      setFormData({
        project_name: project.project_name || '',
        project_type: project.project_type || '',
        priority: project.priority || '中',
        status: project.status || '立项',
        manager_name: project.manager_name || '',
        client_info: project.client_info || '',
        start_date: project.start_date || '',
        end_date: project.end_date || '',
        budget: project.budget || '',
        description: project.description || '',
        objectives: project.objectives || '',
        risk_level: project.risk_level || '中',
        team_members: project.team_members || []
      });
    }
  }, [project]);

  // 处理表单字段变化
  const handleFieldChange = (field, value) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  // 添加团队成员
  const handleAddMember = () => {
    if (newMember.trim() && !formData.team_members.includes(newMember.trim())) {
      setFormData(prev => ({
        ...prev,
        team_members: [...prev.team_members, newMember.trim()]
      }));
      setNewMember('');
    }
  };

  // 移除团队成员
  const handleRemoveMember = (member) => {
    setFormData(prev => ({
      ...prev,
      team_members: prev.team_members.filter(m => m !== member)
    }));
  };

  // 处理表单提交
  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      // 生成项目编号（实际项目中应该由后端生成）
      const projectCode = project ? project.project_code : `PRJ-${new Date().getFullYear()}-${String(Math.floor(Math.random() * 1000)).padStart(3, '0')}`;
      
      const submitData = {
        ...formData,
        project_code: projectCode,
        budget: parseFloat(formData.budget) || 0
      };
      
      onSubmit && onSubmit(submitData);
    } catch (error) {
      console.error('保存项目失败:', error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Container>
      <Card>
        <CardHeader>
          <CardTitle>{project ? '编辑项目' : '创建项目'}</CardTitle>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmit} className="space-y-6">
            {/* 基本信息 */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div className="space-y-2">
                <Label htmlFor="project_name">项目名称 *</Label>
                <Input
                  id="project_name"
                  value={formData.project_name}
                  onChange={(e) => handleFieldChange('project_name', e.target.value)}
                  placeholder="请输入项目名称"
                  required
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="project_type">项目类型 *</Label>
                <Select value={formData.project_type} onValueChange={(value) => handleFieldChange('project_type', value)}>
                  <SelectTrigger>
                    <SelectValue placeholder="请选择项目类型" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="研发">研发</SelectItem>
                    <SelectItem value="工程">工程</SelectItem>
                    <SelectItem value="咨询">咨询</SelectItem>
                    <SelectItem value="其他">其他</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div className="space-y-2">
                <Label htmlFor="priority">优先级</Label>
                <Select value={formData.priority} onValueChange={(value) => handleFieldChange('priority', value)}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="高">高</SelectItem>
                    <SelectItem value="中">中</SelectItem>
                    <SelectItem value="低">低</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div className="space-y-2">
                <Label htmlFor="status">项目状态</Label>
                <Select value={formData.status} onValueChange={(value) => handleFieldChange('status', value)}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="立项">立项</SelectItem>
                    <SelectItem value="执行中">执行中</SelectItem>
                    <SelectItem value="验收">验收</SelectItem>
                    <SelectItem value="结项">结项</SelectItem>
                    <SelectItem value="暂停">暂停</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div className="space-y-2">
                <Label htmlFor="manager_name">项目负责人 *</Label>
                <Input
                  id="manager_name"
                  value={formData.manager_name}
                  onChange={(e) => handleFieldChange('manager_name', e.target.value)}
                  placeholder="请输入项目负责人"
                  required
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="client_info">客户信息</Label>
                <Input
                  id="client_info"
                  value={formData.client_info}
                  onChange={(e) => handleFieldChange('client_info', e.target.value)}
                  placeholder="请输入客户信息"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="start_date">开始时间</Label>
                <Input
                  id="start_date"
                  type="date"
                  value={formData.start_date}
                  onChange={(e) => handleFieldChange('start_date', e.target.value)}
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="end_date">结束时间</Label>
                <Input
                  id="end_date"
                  type="date"
                  value={formData.end_date}
                  onChange={(e) => handleFieldChange('end_date', e.target.value)}
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="budget">项目预算</Label>
                <Input
                  id="budget"
                  type="number"
                  step="0.01"
                  min="0"
                  value={formData.budget}
                  onChange={(e) => handleFieldChange('budget', e.target.value)}
                  placeholder="请输入项目预算"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="risk_level">风险等级</Label>
                <Select value={formData.risk_level} onValueChange={(value) => handleFieldChange('risk_level', value)}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="高">高</SelectItem>
                    <SelectItem value="中">中</SelectItem>
                    <SelectItem value="低">低</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            {/* 项目描述 */}
            <div className="space-y-2">
              <Label htmlFor="description">项目描述</Label>
              <Textarea
                id="description"
                value={formData.description}
                onChange={(e) => handleFieldChange('description', e.target.value)}
                placeholder="请输入项目描述"
                rows={4}
              />
            </div>

            {/* 项目目标 */}
            <div className="space-y-2">
              <Label htmlFor="objectives">项目目标</Label>
              <Textarea
                id="objectives"
                value={formData.objectives}
                onChange={(e) => handleFieldChange('objectives', e.target.value)}
                placeholder="请输入项目目标"
                rows={3}
              />
            </div>

            {/* 团队成员 */}
            <div className="space-y-2">
              <Label>团队成员</Label>
              <div className="flex gap-2">
                <Input
                  value={newMember}
                  onChange={(e) => setNewMember(e.target.value)}
                  placeholder="输入成员姓名后按回车添加"
                  onKeyPress={(e) => {
                    if (e.key === 'Enter') {
                      e.preventDefault();
                      handleAddMember();
                    }
                  }}
                />
                <Button type="button" variant="outline" onClick={handleAddMember}>
                  <Plus className="size-4" />
                </Button>
              </div>
              {formData.team_members.length > 0 && (
                <div className="flex flex-wrap gap-2 mt-2">
                  {formData.team_members.map((member, index) => (
                    <Badge key={index} variant="secondary" className="gap-1">
                      {member}
                      <button
                        type="button"
                        onClick={() => handleRemoveMember(member)}
                        className="ml-1 hover:text-destructive"
                      >
                        <X className="size-3" />
                      </button>
                    </Badge>
                  ))}
                </div>
              )}
            </div>

            {/* 操作按钮 */}
            <div className="flex gap-4 pt-4">
              <Button type="submit" disabled={loading}>
                {loading ? '保存中...' : (project ? '更新项目' : '创建项目')}
              </Button>
              <Button type="button" variant="outline" onClick={onCancel}>
                取消
              </Button>
            </div>
          </form>
        </CardContent>
      </Card>
    </Container>
  );
};

export default ProjectForm; 